<template>
  <div v-if="tableData.length" :style="transverseScroll ? 'overflow: auto;': 'overflow: inherit;'">
    <table class="dragger-table" ref="draggerTable">
      <thead>
        <tr>
          <th v-if="isCheck" class="table-column-checkbox"><a-checkbox @change="handleHeaderCheck" :checked="tableData.length && allChecked"></a-checkbox></th>
          <th v-for="(item, index) in columns" :key="item.key" class="resize-table-th" :style="'width: ' + item.width + 'px'">
            <span class="ant-table-header-column"><span v-if="item.required" class="required">*</span>{{item.displayName}}</span>
            <vue-draggable-resizable
              :key="item.dataIndex || item.key"
              class="table-draggable-handle"
              :w="10"
              :x="(!item.width || typeof item.width === 'string') ? item.defaultWidth : item.width"
              :z="1"
              axis="x"
              :draggable="true"
              :resizable="false"
              @dragging="onDrag($event, item, index)"
            >
            </vue-draggable-resizable>
          </th>
        </tr>
      </thead>
      <draggable :value="tableData" element="tbody" :options="{disabled: disabledDragg}" @update="datadragEnd">
        <tr v-for="(item, index) in tableData" :key="index">
          <td v-if="isCheck" class="table-column-checkbox"><a-checkbox @change="handleCheck($event, item, index)" :checked="checkedData[index]"></a-checkbox></td>
          <td v-for="itm in columns" :key="itm.key" :style="getWidth(itm.width)">
            <a-input-number @mousedown="tdMousedown" @mouseup="tdMouseup" v-if="itm.number && isEdit && itm.summation" :disabled="true" :value="getTotal(itm, item,  tableData, columns)" />
            <a-input @mousedown="tdMousedown" @mouseup="tdMouseup" v-else-if="isEdit && itm.summation" :disabled="true" :value="getTotal(itm, item,  tableData, columns)" /> <!-- 合计  @input="cellInput" -->
            <a-input-number @mousedown="tdMousedown" @mouseup="tdMouseup" v-else-if="itm.number && isEdit && itm.fieldType==='Input'  && (item.add || !itm.dynamic)" v-model="item[itm.name]" :step="itm.step || 0.1" :min="0" placeholder="请输入" :disabled="!item.add && itm.disabled" />
            <!-- item.disabledKey === itm.key  单个单元格禁用  dynamic 当前行动态禁用 add:true 不禁用 false禁用 -->
            <a-tooltip v-else-if="isEdit && itm.fieldType==='Input' && ((!(item.disabledKey === itm.key || itm.disabled)) || (item.add || !itm.dynamic))">
                <template slot="title" v-if="itm.tooltip">
                  {{item[itm.name]}}
                </template>
                <a-input @mousedown="tdMousedown" @mouseup="tdMouseup" v-model="item[itm.name]" placeholder="请输入" :disabled="(item.disabledKey === itm.key || itm.disabled) && !(item.add && itm.dynamic)" @blur="onBlur(itm, item, index)" />             
            </a-tooltip>
            <!-- <div v-else-if="isEdit && itm.fieldType==='Select'  && (item.add || !itm.dynamic)"> -->
              <a-select
                 v-else-if="isEdit && itm.fieldType==='Select'  && (item.add || !itm.dynamic)"
                @mousedown="tdMousedown" @mouseup="tdMouseup"
                :mode="itm.multiple ? 'multiple': 'default'"
                style="width: 100%;"
                show-search
                placeholder="请选择"
                option-filter-prop="children"
                :filter-option="filterOption"
                :allowClear="true"
                v-model="item[itm.name]"
                :disabled="itm.disabled && !(item.add && itm.dynamic)"
                @change="handleSelectChange($event,itm.key)">
                  <a-select-option v-for="seletItem in itm.selectData" :key="seletItem[itm.selectField ? itm.selectField.name : 'name']">
                    {{seletItem[itm.selectField ? itm.selectField.value : 'value']}}
                  </a-select-option>
                  <a-icon slot="clearIcon" type="close"></a-icon>
              </a-select>
            <!-- </div> -->
             
            <a-date-picker v-else-if="isEdit && itm.fieldType==='Date'  && (item.add || !itm.dynamic)" @mousedown="tdMousedown" @mouseup="tdMouseup"
              :locale="locale" v-model="item[itm.name]" :valueFormat="itm.format" placeholder="请选择"
              :disabled="itm.disabled && !(item.add && itm.dynamic)" />
            <span @mousedown="tdMousedown" @mouseup="tdMouseup" v-else-if="itm.url">
              <a-tooltip placement="topLeft" :title="item.title">
                <img src="@/assets/single/doc.png" style="width: 10px;height: 8px;margin-right: 10px;" v-if="item.checkOut"/>
              </a-tooltip>
              <a @click="routerPage(item)">{{item[itm.name]}}</a>
            </span>
            <a-tooltip v-else-if="isEdit && (item.disabledKey === itm.key || itm.disabled)">
                <template slot="title" v-if="item[itm.name] || item[itm.name] === 0">
                  {{item[itm.name]}}
                </template>
                <div class="frobidden">{{item[itm.name]}}</div>
            </a-tooltip>
            <a-tooltip v-else>
              <template slot="title"> 
                {{item[itm.name]}}
              </template>
              <span @mousedown="tdMousedown" @mouseup="tdMouseup">{{item[itm.name]}}</span>
            </a-tooltip>
          </td>
        </tr>
      </draggable>
    </table>
  </div>
  <div v-else class="dragger-table empty-box">
    <div class="tr">
      <span class="th"><a-checkbox @change="handleHeaderCheck" :checked="false"></a-checkbox></span>
      <span class="th" v-for="item in columns" :key="item.key"><span v-if="item.required" class="required">*</span>{{item.displayName}}</span>
    </div>
    <empty></empty>
  </div>
</template>
<script>
import draggable from"vuedraggable";
import empty from '@/components/empty/empty'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import Vue from 'vue'
import VueDraggableResizable from 'vue-draggable-resizable'
Vue.component('vue-draggable-resizable', VueDraggableResizable)
export default {
  components: {
    draggable,
    empty
  },
  props: {
    isEdit: {
      type: Boolean,
      default: true
    },
    isCheck: {
      type: Boolean,
      default: true
    },
    columns: {
      type: Array,
      default: () => []
    },
    tableData: {
      type: Array,
      default: () => []
    },
    disabledDraggProps: {
      type: Boolean,
      default: false
    },
    // 是否可以横向滚动
    transverseScroll: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      locale,
      disabledDragg: this.disabledDraggProps, // 禁止拖拽
      allChecked: false,
      keyObj: null,
      checkedData: [],
      newTableData: this.tableData,
      initWidth: false
    };
  },
  computed: {
  },
  watch: {
    checkedData(val) {
      if (!val.length) {  this.allChecked = false }
      else {
        this.allChecked = val.filter(item => item).length === this.tableData.length
      }
      let selectedData = []
      this.tableData.forEach((item, index) => {
        if (val[index]) {
          selectedData.push(index)
        }
      })
      this.$emit('selectedData', selectedData)
    }
  },
  updated() {
    // this.$nextTick(() => {
    //   console.log('updated', this.columns)
    //   this.initSetWidth()
    // })
  },
  methods: {
    initSetWidth() {
      if (this.initWidth) return
      let thArr = Array.from(Array.from(this.$refs.draggerTable.children)[0].getElementsByTagName('th'))
      thArr.forEach((thDom, index) => {
        let width = thDom.getBoundingClientRect().width
        if (width > 0) {
          this.initWidth = true
          let columnIndex = index
          if (this.isCheck && index > 0) {
            columnIndex--
            this.$set(this.columns[columnIndex], 'width', width)
          } else {
            this.$set(this.columns[columnIndex], 'width', width)
          }
        }
      })
    },
    // td选择时禁止拖拽 负责不能选中复制粘贴
    tdMousedown(e) {
      e.stopPropagation();
      this.disabledDragg = true
    },
    tdMouseup(e) {
      e.stopPropagation();
      this.disabledDragg = false
    },
    onDrag(x, col, index) {
      this.$set(this.columns[index], 'width', Math.max(x, 40))
    },
    routerPage(val) {
      this.$emit("routerPage", val);
    },
    cellInput() {
      this.$emit('update:tableData', this.newTableData)
    },
    handleSelectChange(val,colKey) {
      this.$emit('change',val,colKey)
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    getWidth(width) {
      if (!width) return
      return `width: ${ (typeof width === 'number' || !width.includes('%')) ? width + 'px' : width }`
    },
    getTotal(itm, item,  tableData, columns) {
      let total = itm.handle(item, tableData, columns)
      // let allTotal = 0
      // tableData.forEach(item => {
      //   allTotal += item.totalAmount
      // })
      // this.$emit('getTotal', allTotal)
      this.$emit('update:tableData', tableData)
      return total
    },
    onBlur(itm, item, index){
      this.$emit('blur', itm, item, index)
    },
    // 表头checkbox
    handleHeaderCheck() {
      let selectedData = this.checkedData.filter(item => item)
      // 已经全选，设为全不选
      if (!this.tableData.length || selectedData.length === this.tableData.length) {
        this.checkedData = []
        this.allChecked = false
      } else {
        // 没有选中的 或 有选中的 设为全部选中
        this.allChecked = true
        let checkedData = new Array(this.tableData.length)
        checkedData.fill(true)
        this.checkedData = checkedData
      }
    },
    // 表格checkbox
    handleCheck(e, item, index) {
      this.$set(this.checkedData, [index], e.target.checked)
    },
    //拖动中与拖动结束
    getdata(evt) {
      // console.log(evt);
    },
    datadragEnd(evt) {
      let oldIndex = evt.oldIndex
      let newIndex = evt.newIndex
      let d = this.tableData.splice(oldIndex, 1)
      this.tableData.splice(newIndex, 0, ...d)
      this.$emit('update:tableData', this.tableData)
    }
  }
}
</script>
<style lang="less" scoped>
  .dragger-table{
    table-layout: fixed;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    font-size: 14px;
    font-variant: tabular-nums;
    line-height: 1.5;
    list-style: none;
    font-feature-settings: 'tnum';
    position: relative;
    clear: both;
    width: 100%;
    white-space: nowrap;
    .table-column-checkbox {
      width: 30px;
      text-align: center;
    }
    tr, .tr {
      height: 35px;
    line-height: 35px;
      cursor: pointer;
      &:hover{
        background: #f0f7ff;
      }
      th, td, .header, .th{
        border-bottom: 1px solid #e8e8e8;
        transition: background 0.3s ease;
        box-sizing: content-box;
        padding: 0 16px;
        border: 1px solid #eee;
      }
      th, .th{
        background: #f6f6f6;
        color: rgba(0, 0, 0, 0.85);
        border-right: 1px solid #eee;
        &:hover{
          background: #f6f6f6;
        }
      }
      td{
        color: rgba(0, 0, 0, 0.65);
        word-wrap: break-word;
        word-break: break-all;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        max-width: 300px;
        position: relative;
        /deep/ .ant-input{
          height: 24px;
        }
        /deep/ .ant-select-selection--single{
          height: 24px;
        }
        /deep/ .ant-select-selection--single .ant-select-selection__rendered{
          line-height: 1.5;
        }
        /deep/ .ant-input-number, /deep/ .ant-input-number-input{
          height: 24px;
        }
        /deep/ .ant-input-number{
          width: 110px;
        }
        /deep/ .ant-input-number-disabled{
          color: #999;
        }
        // /deep/ .ant-calendar-picker{
        //   top: 50%;
        //   transform: translateY(-50%);
        // }
        /deep/ .frobidden{
          color: #999;
          background-color: #f5f5f5;
          border: 1px solid #d9d9d9;
          border-radius: 4px;
          cursor: not-allowed;
          width: 100%;
          height: 24px;
          line-height: 1;
          padding: 4px 11px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
    .required{
      color: red;
      margin-right: 5px;
    }
  }
  .empty-box{
    .tr{
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: #f6f6f6;
      .th{
        flex: auto;
        &:nth-of-type(1) {
          flex: none;
        }
      }
    }
  }
</style>